from flask import Blueprint,render_template,request,current_app,redirect,url_for,flash
from decorators import login_required
from models.books import BookModel, BoardModel
from models.user import UserModel
from exts import db
from sqlalchemy import text
from forms.userform import addEmpForm
from forms.bookform import bookForm
from forms.boardform import BoardForm
from flask_paginate import Pagination

bp = Blueprint('cms',__name__,url_prefix="/cms")


@bp.route("/")
@login_required
def cms_index():
    return render_template("cms/cms_home.html")


@bp.route("/book/home")
@login_required
def cms_book_home():
    return render_template("cms/cms_book.html")


@bp.route("/book/info")
@login_required
def cms_book_info():
    page = request.args.get("page",type=int,default=1)
    boards = BoardModel.query.filter_by(is_active=1).all()
    book = BookModel.query.filter_by(is_active=1).first()
    board_id=request.args.get("board_id",type=int,default=book.id)
    start = (page-1)*current_app.config.get("PER_PAGE_COUNT")
    end = start + current_app.config.get("PER_PAGE_COUNT")
    # 查询对象
    query_obj = BookModel.query.filter_by(is_active=True).order_by(BookModel.create_time.desc())
    if board_id:
        query_obj = query_obj.filter_by(board_id=board_id)

    total = query_obj.count()
    books = query_obj.slice(start,end)
    # 分页对象
    pagination = Pagination(bs_version=4,page=page,total=total,outer_window=1,inner_window=2,alignment="center")
    context={
        "pagination":pagination,
        "books":books,
        "boards":boards,
        "current_board_id":board_id
    }
    return render_template("cms/cms_book_info.html",**context)


# 修改图书状态
@bp.route("/book/active/<int:book_id>")
@login_required
def active_btn(book_id):
    book = BookModel.query.get(book_id)
    is_active = request.args.get("is_active",type=int)
    print(is_active)
    if is_active == None:
        return {'status':403,'message':"参数错误,请传入is_active"}
    book.is_active = bool(is_active)
    db.session.commit()
    return {"status":200,"message":"发送成功"}


# 查询所有借阅记录
@bp.route("/borrow")
@login_required
def borrow_info():
    sql = text("SELECT book.name as name,user.id as user_id,book.id as book_id, user.username as username,book_table_user.borrow_time as borrow_time," \
         "book_table_user.is_return as is_return  FROM book,book_table_user," \
         "user WHERE book.id=book_table_user.book_id AND user.id=book_table_user.user_id ORDER BY borrow_time desc ")

    res = db.session.execute(sql).fetchall()
    return render_template("cms/cms_book_borrow.html",books=res)


# 修改借书状态
@bp.post("/update/borrow_status")
@login_required
def update_borrow_info():
    user_id = request.form.get("user_id")
    book_id = request.form.get("book_id")
    user_id = int(user_id)
    book_id = int(book_id)
    print(user_id)
    print(book_id)
    if user_id == None or book_id ==None:
        return {"status":403,"message":"参数错误"}
    book = BookModel.query.get(book_id)
    book.is_borrowed = False
    sql = text(f"Update book_table_user set is_return=1 WHERE user_id ={user_id} and book_id={book_id}")
    db.session.execute(sql)
    db.session.commit()
    return {"status":200,"message":"还书完成"}


# 新增图书
@bp.route("/book/add",methods=["POST",'GET'])
@login_required
def add_book():
    boards = BoardModel.query.filter_by(is_active=1).all()
    if request.method=='GET':
        return render_template("cms/cms_add_book.html",boards=boards)
    else:
        form = bookForm(request.form)
        if form.validate():
            name = form.name.data
            board_id = form.board_id.data
            author_name = form.author_name.data
            desc = form.desc.data
            book = BookModel(name=name,board_id=board_id,author_name=author_name,desc=desc)
            db.session.add(book)
            db.session.commit()
            return redirect(url_for("cms.cms_book_info",board_id=board_id))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for("cms.add_book"))


# 分类管理首页
@bp.route("/board")
@login_required
def board_index():
    return render_template("cms/cms_board.html")


# 编辑分类
@bp.route("/board/edit")
@login_required
def board_edit():
    boards = BoardModel.query.all()
    return render_template("cms/cms_board_edit.html",boards=boards)


# 编辑分类状态
@bp.put("/board/active/<int:board_id>")
@login_required
def board_active(board_id):
    is_active = request.form.get("is_active")
    print(is_active)
    board = BoardModel.query.get(board_id)
    board.is_active = bool(is_active)
    db.session.commit()
    return {"status":200,"message":"数据修改成功"}


@bp.put("/board/name/<int:board_id>")
@login_required
def board_name(board_id):
    board_name = request.form.get("board_name")
    board = BoardModel.query.get(board_id)
    board.name = board_name
    db.session.commit()
    return {"status":200,"message":"修改成功"}


# 添加分类
@bp.route("/board/add",methods=['GET',"POST"])
@login_required
def board_add():
    if request.method == 'GET':
        return render_template("cms/cms_board_add.html")
    else:
        form = BoardForm(request.form)
        if form.validate():
            name = form.name.data
            board = BoardModel(name=name)
            db.session.add(board)
            db.session.commit()
            return redirect(url_for("cms.board_edit"))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for("cms.board_add"))


# 前台用户
@bp.route("/front_user",methods=['GET','PUT'])
@login_required
def cms_userFront():
    if request.method=="GET":
        users = UserModel.query.filter_by(is_staff=0).all()
        return render_template("cms/front_user.html",users=users)
    else:
        user_id = request.form.get("user_id")
        user_id = int(user_id)
        is_active= request.form.get("is_active")
        print(is_active)
        print(user_id)
        user = UserModel.query.get(user_id)
        user.is_active = int(is_active)
        db.session.commit()
        return {"status":200,"message":"修改成功!"}


@bp.route("/cms_user")
@login_required
def cms_user():
    cms_users = UserModel.query.filter_by(is_staff=1).all()
    return render_template("cms/cms_user.html",users=cms_users)


@bp.put("/cms_user/<int:user_id>")
@login_required
def cms_user_active(user_id):
    is_active= request.form.get("is_active")
    is_active = int(is_active)
    user = UserModel.query.get(user_id)
    user.is_active = is_active
    db.session.commit()
    return {"status":200,"message":"成功!"}


@bp.route("/cms_user/add",methods=["POST",'GET'])
@login_required
def cms_user_add():
    if request.method =='GET':
        users = UserModel.query.filter_by(is_staff=0).all()
        return render_template("cms/cms_user_add.html",users=users)
    else:
        user_id = request.form.get("user_id")
        user = UserModel.query.get(int(user_id))
        user.is_staff=1
        user.role_id=1
        db.session.commit()
        return redirect(url_for("cms.cms_user"))
